<?php
/**
 * User: zhangligang
 * Email: tzhang2450@163.com
 * Date: 2018/11/24
 * Time: 23:55
 */

namespace App\Http\Controllers\V1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use App\Providers\MyJwt;
use App\Http\Services\UserService;

class UserController extends Controller
{
    protected $jwtCode;

    public function __construct(Request $request)
    {
        $authorization = $request->header('Authorization');
        $jwt = new MyJwt();
        $jwtCode = $jwt->decode($authorization, MyJwt::ENCODE_KEY);
        if (!$jwtCode || !array_key_exists('uid', $jwtCode)) {
            $this->sendJson([], 4031, '请登录');
        }
        if (!array_key_exists('role', $jwtCode) || !in_array($jwtCode['role'], [1, 2, 3])) {
            $this->sendJson([], 4032, '非法请求');
        }
        if (!array_key_exists('timeout', $jwtCode) || $jwtCode['timeout'] < time()) {
            $this->sendJson([], 4031, '请登录');
        }

        $cacheKey = sprintf('fc:login:uid:%d', $jwtCode['uid']);
        $cacheData = Redis::get($cacheKey);
        if (!$cacheData || $cacheData < time()) {
            Redis::setex($cacheKey, 0, null);
            $this->sendJson([], 4031, '请登录');
        }
        $this->jwtCode = $jwtCode;
    }

    public function check() {
        $this->sendJson(['role' => $this->jwtCode['role']]);
    }

    protected function getUser()
    {
        $uid = $this->jwtCode['uid'];
        return UserService::getById($uid);
    }
}